from spargameproject.spargame.game.engine.game_engine import PlayHandler
from spargameproject.spargame.models import GamePlayer
from spargameproject.util import inPlaceUnique

class DryHandler(PlayHandler):
  def getType(self):
    return 'dry'

  def handlePlay(self, play, game_engine):
    session = play.game.getMetadata('session')
    play.setMetadata('session', session)
    print 'Just handled a play of type: ' + self.getType() + '-' + play.getMetadata("cards")
    if play.game.getMetadata('ready'):
      return ['Can\'t dry when round has already begun'], {}
    card_indeces_str = play.getMetadata('card_indeces')
    if not card_indeces_str:
      return ['Please select one or more cards'], {}
    card_indeces = [int(x) for x in card_indeces_str.split(",")]
    game_player = GamePlayer.objects.get(game=play.game, player=play.player)
    hand = game_player.getMetadata('hand')[session]
    for index in card_indeces:
      if hand[index].rank.value > 7:
        return ['You can only dry a 6 or a 7'], {}
    response = {}
    errors = []

    # update the current_cards_left metadata
    cards_left = game_player.getMetadata('cards_left')
    for card_index in card_indeces:
      cards_left[card_index] = None

    current_cards_left = [card for card in cards_left if card]
    game_player.setMetadata('current_cards_left', current_cards_left)
    game_player.setMetadata('cards_left', cards_left)

    current_dry_card_indeces = game_player.getMetadata('dry_card_indeces')
    card_indeces = inPlaceUnique(card_indeces)
    end_card_number = 5 - len(current_dry_card_indeces)
    start_card_number = end_card_number - len(card_indeces)
    card_number_array = [i for i in range(start_card_number, end_card_number)]
    card_numbers = ','.join([str(x) for x in card_number_array])
    response['card_numbers'] = card_numbers
    play.setMetadata('card_numbers', card_number_array)

    # Build the display message and update cards_left.
    message = 'Dried %s card%s' % (len(card_indeces), 's' if len(card_indeces) > 1 else '')
    play.setMetadata('message', message)
    response['message'] = message
    card_indeces.extend(current_dry_card_indeces)
    game_player.setMetadata('dry_card_indeces', card_indeces)

    return errors, response
